﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;

namespace TBG.TBG_F
{
    class GameManager
    {
        Player _Player;
        AI _AI;
        TileWorldManager _TWM;
        Timer _Timer;

        KeyboardState previousKS;

        //CONSTRUCTOR
        public GameManager(ContentManager content)
        {
            _Player = new Player(content);
            _AI = new AI(content);
            _TWM = new TileWorldManager(content);
            _Timer = new Timer(content);
        }
        //UPDATE
        public void Update(GameTime gameTime)
        {
            _Player.Update(gameTime);
            _TWM.Update(gameTime);
            _Timer.Update(gameTime);
            if (_Timer.PlayerTurn)
            {
                inputListener(Keyboard.GetState());
                PlayerMoveClick();
            }

            //takes Player as a parameter to know its target
            if (!_Timer.PlayerTurn)
            {
                _AI.Update(gameTime, _Player);
            }
        }
        //DRAW
        public void Draw(SpriteBatch spriteBatch)
        {
            _TWM.Draw(spriteBatch);
            _Player.Draw(spriteBatch);
            _AI.Draw(spriteBatch);
            _Timer.Draw(spriteBatch);
        }
        //INPUT LISTENER FOR ACTION PERFORMED
        private void inputListener(KeyboardState currectKS)
        {
            if (currectKS.IsKeyDown(Keys.M) && previousKS.IsKeyUp(Keys.M))
            {
                //TOOD: MOVE
                PlayerMove();
            }
            if (currectKS.IsKeyDown(Keys.A) && previousKS.IsKeyUp(Keys.A))
            {
                //TODO: ATTACK
                _Player.Attack(_AI);
            }
            previousKS = currectKS;
        }

        private void PlayerMove()
        {
            _TWM.selectSqaures(_Player._Position);              //Select surrounding squares based on Player position
        }

        private void PlayerMoveClick()
        {
            MouseState MS = Mouse.GetState();                   //retrieve mouse state
            Rectangle MSRECT = new Rectangle(MS.X, MS.Y, 1, 1); //Use mouse state to create rectangle which we will use to check for moving

            if (MS.LeftButton == ButtonState.Pressed)
            {
                foreach (Tile tile in _TWM.TILES)
                {
                    if (tile._State == TileStates.Blocked)
                    {
                        if (MSRECT.Intersects(tile.getBoundingRect()))
                        {
                            _Player._Position = tile._Position;
                        }
                    }
                }
            }
        }
    }
}
